/**
 * 
 */
package com.et114.modules.extend.acegi;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;

import javax.sql.DataSource;

import java.util.*;

import org.acegisecurity.userdetails.UsernameNotFoundException;

import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.jdbc.object.MappingSqlQuery;
import org.springframework.util.Assert;

import com.et114.modules.org.vo.UserVo;

/*
 * @author guanhw
 */
public class AwCasPrincipalConvertImpl extends JdbcDaoSupport implements IAwCasPrincipalConvert {
	public String convertQuery  ;

    protected MappingSqlQuery authoritiesByUsernameMapping;
    protected MappingSqlQuery usersByUsernameMapping;
	
    // must be init property id , loginname , password , workflg
	public UserVo convert( String principal ) throws UsernameNotFoundException  {
		UsersByUsernameMapping u = new UsersByUsernameMapping( this.getDataSource ( ) ); 
		List users =  u.execute ( principal ) ;
		if ( users.size ( ) == 0 ) new UsernameNotFoundException( "Not Found!" ) ; 
		return ( UserVo )users.get ( 0  ) ; 
	} 
	
    /**
     * Query object to look up a user.
     */
	protected class UsersByUsernameMapping extends MappingSqlQuery {
		protected UsersByUsernameMapping ( DataSource ds ) {
			super ( ds , convertQuery );
			declareParameter ( new SqlParameter ( Types.VARCHAR ) );
			compile ( );
		}
		
		protected Object mapRow ( ResultSet rs , int rownum )
				throws SQLException {
			UserVo user = new UserVo( ) ; 
			user.setUserId ( new Long ( rs.getLong ( 1 ) ) ) ; 
			user.setLoginName ( rs.getString ( 2 ) ) ; 
			user.setPassword ( rs.getString ( 3 ) ) ; 
			user.setWorkFlg ( Boolean.valueOf ( rs.getBoolean ( 4 ) ) ) ; 
			user.setLastModPassTime ( rs.getDate (  5 ) ) ; 
            return user;
        }
    }

	public String getConvertQuery ( ) {
		return convertQuery;
	}

	public void setConvertQuery ( String convertQuery ) {
		Assert.notNull (  convertQuery , "convertQuery must be set !" ) ;
		this.convertQuery = convertQuery;
	}



}
